package com.yenlien.traceyun.plant.service;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.plant.controller.vo.ExportVo;
import com.yenlien.traceyun.plant.controller.vo.StatisticsVO;
import com.yenlien.traceyun.plant.dao.ShiJiRuiTongDao;
import com.yenlien.traceyun.plant.entity.ShiJiRuiTong;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.servlet.ServletOutputStream;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class DeGeBigScreenService {
    @Autowired
    private ShiJiRuiTongDao shiJiRuiTongDao;


    // 乐橙云  18980066008  cdyl321321   https://oauth.imou.com/login?client=open
//    public static final String appId = "lc90799dfdeee94286";
//    public static final String appSecret = "b8da69d00c0f47059df3b278ae41f0";

    @Value("${dege.daHua.appId}")
    public String appId;
    @Value("${dege.daHua.appSecret}")
    public String appSecret;

    public String token;
    public String serial;   // 设备序列号

    static Map<String, Object> tokenMap = new HashMap();


    public static void main(String[] args) {
        new DeGeBigScreenService().getToken();
    }

    public void getToken() {
        if (tokenMap.containsKey("token")) {
            LocalDateTime tokenTime = (LocalDateTime) tokenMap.get("tokenTime");
            LocalDateTime now = LocalDateTime.now();
            if (Duration.between(tokenTime, now).toDays() <= 2) {
                return;
            }
        }
        JSONObject params = new JSONObject();
        params.put("id", RandomStringUtils.randomNumeric(20));
        JSONObject system = new JSONObject();
        system.put("ver", "1.0");
//        system.put("appId", appId);
        system.put("appId", "lc90799dfdeee94286");
        system.put("nonce", RandomStringUtils.randomNumeric(32));
        system.put("time", new Date().getTime() / 1000);
//        String sign = "time:" + system.getString("time") + ",nonce:" + system.getString("nonce") + ",appSecret:" + appSecret;
        String sign = "time:" + system.getString("time") + ",nonce:" + system.getString("nonce") + ",appSecret:" + "b8da69d00c0f47059df3b278ae41f0";
        system.put("sign", SecureUtil.md5(sign));
        params.put("system", system);
        JSONObject param = new JSONObject();
        params.put("params", param);
        JSONObject result = JSONObject.parseObject(HttpUtil.post("https://openapi.lechange.cn/openapi/accessToken", JSONObject.toJSONString(params))).getJSONObject("result");
        if ("0".equals(result.getString("code"))) {
            token = result.getJSONObject("data").getString("accessToken");
            tokenMap.put("token", token);
            tokenMap.put("tokenTime", LocalDateTime.now());
        } else {
            throw new BusinessException("获取乐橙云Token失败: " + result.getString("msg"));
        }
    }


    /**
     * 返回设备token
     * @return
     */
    public String getToken1() {
        if (tokenMap.containsKey("token")) {
            LocalDateTime tokenTime = (LocalDateTime)tokenMap.get("tokenTime");
            LocalDateTime now = LocalDateTime.now();
            if (Duration.between(tokenTime, now).toDays() <= 2L)
                return tokenMap.get("token").toString();
        }
        JSONObject params = new JSONObject();
        params.put("id", RandomStringUtils.randomNumeric(20));
        JSONObject system = new JSONObject();
        system.put("ver", "1.0");
        system.put("appId", "lc90799dfdeee94286");
        system.put("nonce", RandomStringUtils.randomNumeric(32));
        system.put("time", Long.valueOf((new Date()).getTime() / 1000L));
        String sign = "time:" + system.getString("time") + ",nonce:" + system.getString("nonce") + ",appSecret:b8da69d00c0f47059df3b278ae41f0";
        system.put("sign", SecureUtil.md5(sign));
        params.put("system", system);
        JSONObject param = new JSONObject();
        params.put("params", param);
        JSONObject result = JSONObject.parseObject(HttpUtil.post("https://openapi.lechange.cn/openapi/accessToken", JSONObject.toJSONString(params))).getJSONObject("result");
        if ("0".equals(result.getString("code"))) {
            this.token = result.getJSONObject("data").getString("accessToken");
            tokenMap.put("token", this.token);
            tokenMap.put("tokenTime", LocalDateTime.now());
            return result.getJSONObject("data").getString("accessToken");
        }
        throw new BusinessException("" + result.getString("msg"));
    }

    /**
     * 根据accessToken和页码,条数请求返回设备列表,设备列表包含设备在线状态
     * @param accessToken
     * @return
     */
    public JSONArray getDevicePage(String accessToken) {
        JSONObject params = new JSONObject();
        params.put("id", RandomStringUtils.randomNumeric(20));
        JSONObject system = new JSONObject();
        system.put("ver", "1.0");
        system.put("appId", "lc90799dfdeee94286");
        system.put("nonce", RandomStringUtils.randomNumeric(32));
        system.put("time", Long.valueOf((new Date()).getTime() / 1000L));
        String sign = "time:" + system.getString("time") + ",nonce:" + system.getString("nonce") + ",appSecret:b8da69d00c0f47059df3b278ae41f0";
        system.put("sign", SecureUtil.md5(sign));
        params.put("system", system);
        JSONObject param = new JSONObject();
        param.put("token", accessToken);
        param.put("pageSize", Integer.valueOf(50));
        param.put("page", Integer.valueOf(1));
        param.put("source", "bindAndShare");
        params.put("params", param);
        JSONObject result = JSONObject.parseObject(HttpUtil.post("https://openapi.lechange.cn/openapi/listDeviceDetailsByPage", JSONObject.toJSONString(params))).getJSONObject("result");
        if ("0".equals(result.getString("code"))) {
            JSONArray deviceList = result.getJSONObject("data").getJSONArray("deviceList");
            return deviceList;
        }
        throw new BusinessException("" + result.getString("msg"));
    }

    public void controlMovePTZ(String operation, String duration) {
        JSONObject params = new JSONObject();
        params.put("id", RandomStringUtils.randomNumeric(20));
        JSONObject system = new JSONObject();
        system.put("ver", "1.0");
        system.put("appId", appId);
        system.put("nonce", RandomStringUtils.randomNumeric(32));
        system.put("time", new Date().getTime() / 1000);
        String sign = "time:" + system.getString("time") + ",nonce:" + system.getString("nonce") + ",appSecret:" + appSecret;
        system.put("sign", SecureUtil.md5(sign));
        params.put("system", system);
        JSONObject param = new JSONObject();
        param.put("token", token);
        param.put("deviceId", serial);
        param.put("channelId", "0");
        param.put("operation", operation);
        param.put("duration", duration);
        params.put("params", param);
        JSONObject result = JSONObject.parseObject(HttpUtil.post("https://openapi.lechange.cn/openapi/controlMovePTZ", JSONObject.toJSONString(params))).getJSONObject("result");
        if (!"0".equals(result.getString("code"))) {
            throw new BusinessException("转向失败: " + result.getString("msg"));
        }
    }

    public void zoomFocus(String type, String zoomFocus) {
        JSONObject params = new JSONObject();
        params.put("id", RandomStringUtils.randomNumeric(20));
        JSONObject system = new JSONObject();
        system.put("ver", "1.0");
        system.put("appId", appId);
        system.put("nonce", RandomStringUtils.randomNumeric(32));
        system.put("time", new Date().getTime() / 1000);
        String sign = "time:" + system.getString("time") + ",nonce:" + system.getString("nonce") + ",appSecret:" + appSecret;
        system.put("sign", SecureUtil.md5(sign));
        params.put("system", system);
        JSONObject param = new JSONObject();
        param.put("token", token);
        param.put("deviceId", serial);
        param.put("channelId", "0");
        param.put("type", type);
        param.put("zoomFocus", zoomFocus);
        params.put("params", param);
        JSONObject result = JSONObject.parseObject(HttpUtil.post("https://openapi.lechange.cn/openapi/setZoomFocus", JSONObject.toJSONString(params))).getJSONObject("result");
        if (!"0".equals(result.getString("code"))) {
            throw new BusinessException("变焦失败: " + result.getString("msg"));
        }
    }


    public List<ShiJiRuiTong> getStatistics(StatisticsVO statisticsVO) {
        return shiJiRuiTongDao.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            String type = statisticsVO.getType();
            String beginTime = statisticsVO.getBeginTime();
            String endTime = statisticsVO.getEndTime();
            if (StringUtils.isNotBlank(type)) {
                predicates.add(criteriaBuilder.equal(root.get("type"), type));
            }
            if (StringUtils.isNotBlank(beginTime)) {
                predicates.add(criteriaBuilder.greaterThan(root.get("Ctime"), beginTime));
            }
            if (StringUtils.isNotBlank(endTime)) {
                predicates.add(criteriaBuilder.lessThan(root.get("Ctime"), endTime));
            }
            if (StringUtils.isNotBlank(statisticsVO.getEquipmentId())) {
                predicates.add(criteriaBuilder.equal(root.get("equipmentId"), statisticsVO.getEquipmentId()));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        });
    }

    public ExcelWriter exportExcel(StatisticsVO statisticsVO, ServletOutputStream outputStream) {
        ExcelWriter excelWriter = EasyExcel.write(outputStream, ExportVo.class).build();
        //分页查询
        WriteSheet writeSheet = EasyExcel.writerSheet("采购记录").build();
        do {
            //查询
            List<ShiJiRuiTong> statistics = getStatistics(statisticsVO);
            List<ExportVo> list = new ArrayList<>();
            ExportVo exportVo;
            for (ShiJiRuiTong statistic : statistics) {
                exportVo = new ExportVo();
                exportVo.setCtime(statistic.getCtime());
                exportVo.setEquipmentName(statistic.getEquipmentName());
                exportVo.setParamName(statistic.getParamName());
                exportVo.setParamUnit(statistic.getParamUnit());
                exportVo.setParamVal(statistic.getParamVal());
                list.add(exportVo);
            }
            //判空
            if (statistics != null) {
                excelWriter.write(list, writeSheet);
                break;
            }
//            //设置自增序号
//            long order = 1;
//            for (StockRecordInfoRequest record : list) {
//                record.setOrder(order ++);
//            }
            //写入excel
            excelWriter.write(list, writeSheet);
            list.clear();
        } while (true);
        return excelWriter;
    }
}
